package br.com.portalecbahia.connectionservices;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import blueprint.software.blueframe.synchronize.HTTPConnect;
import br.com.portalecbahia.dao.MatchDAO;
import br.com.portalecbahia.dao.MediaDAO;
import br.com.portalecbahia.dao.NewsDAO;
import br.com.portalecbahia.listner.AllDataListeners;
import br.com.portalecbahia.util.PortalECBahiaUtil;

public class SynchronizeAllData extends AsyncTask<Void, Void, Boolean> {

	private AllDataListeners listeners;
	private HTTPConnect connect;
	private Context context;
	private NewsDAO newsDAO;
	private MediaDAO mediaDAO;
	private MatchDAO matchDAO;

	public SynchronizeAllData(Context context){
	
		this.context = context;
		
		this.listeners = (AllDataListeners)context;
	
	}
	
	@Override
	protected void onPreExecute() {
	
	}
	
  
    @Override
    protected void onPostExecute(Boolean result) {               
        if(result == true){
        	new NewsDAO(context).getLimits();
        	listeners.onSynchronizeAllDataComplete(true);
        }
    
    }

    @Override
	protected Boolean doInBackground(Void... params) {
		try{
			connect = new HTTPConnect(PortalECBahiaUtil.urlServer+"/FindAllData");
			JSONObject jsonObject =  connect.getObject("", null);
			
			if(jsonObject!=null){
				JSONArray jsonArray = jsonObject.getJSONArray("news");
				newsDAO = new NewsDAO(context);
				newsDAO.removeAll();
				newsDAO.insert(jsonArray);	
				newsDAO.getLimits();
				
				jsonArray = jsonObject.getJSONArray("media");
				mediaDAO = new MediaDAO(context);
				mediaDAO.removeAll();
				mediaDAO.insert(jsonArray);	
				
				jsonArray = jsonObject.getJSONArray("match");
				matchDAO = new MatchDAO(context);
				matchDAO.removeAll();
				matchDAO.insert(jsonArray);	
			}
			
		}catch (Exception e) {
			Log.e(PortalECBahiaUtil.TAG, e.toString());
			return  false;
		}
		return true;
		
	}
}

